package org.hackystat.linkedservicedata.ui.issues;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import org.hackystat.linkedservicedata.client.LinkedServiceDataClientException;
import org.hackystat.linkedservicedata.resource.linkedservicedata.LinkedServiceDataResource;
import org.hackystat.linkedservicedata.ui.LinkedServiceDataUI;
import org.hackystat.linkedservicedata.vocabularies.BaetleVocab;
import org.hackystat.linkedservicedata.vocabularies.CommontagVocab;
import org.hackystat.linkedservicedata.vocabularies.HackystatConstants;
import org.hackystat.linkedservicedata.vocabularies.HackystatVocab;
import org.hackystat.sensorbase.resource.sensordata.jaxb.SensorData;
import org.hackystat.utilities.tstamp.Tstamp;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.NodeIterator;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.vocabulary.OWL;
import com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.vocabulary.RDFS;

/**
 * Panel to list and edit all the available issues.
 *
 * @author Myriam Leggieri.
 *
 */
public class IssuesPanel extends JPanel implements KeyListener, ActionListener {

  /**
   * Prefix to identify that one of the 'edit' button has been pressed
   */
  private static final String EDITPREFIX = "EDIT_";

  /**
   * Prefix to identify that one of the 'triplify' button has been pressed
   */
  private static final String TRIPLIFYPREFIX = "TRIPLIFY_";

  /**
   * Prefix to identify that one of the 'save' button has been pressed
   */
  private static final String SAVEPREFIX = "SAVE_";

  /**
   * Prefix to identify that one of the 'ok' button has been pressed
   */
  private static final String OKPREFIX = "OK_";

  /** RDF model containing a list of stored issues. */
  private Model issuesListModel = null;

  /** List of RDF model containing stored issue's profiles. */
  private LinkedList<Model> profilesModelList = null;

  /**
   * List of issue profile's data. Each profile is associated with text fields containing its data
   * which will become editable if one requires to edit them.
   */
  private HashMap<IssueProfile, LinkedList<JTextField>> profilesList = null;

  /** Parent frame. */
  private LinkedServiceDataUI mainframe = null;

  /** Dialog used for displaying the 'please wait' window. */
  private JDialog dialog = null;

  /** Clear cache button. */
  private JButton clearCacheButton = null;

  /**
   * Edit button. Each edit button will be associated with an action command starting with 'edit_'
   * and ending with the correspondent user profile's email
   */
  private JButton editButton = null;

  /** Triplify all button. */
  private JButton triplifyAllButton = null;

  /** Triplify one profile button. */
  private JButton triplifyOneButton = null;

  /** Action label. */
  private JLabel actionLabel = null;

  /** Email label. */
  private JLabel assignedToLabel = null;

  /** Nickname label. */
  private JLabel typeLabel = null;

  /** Tags label. */
  private JLabel tagsLabel = null;

  /** Tags value label. */
  private JLabel tagsValueLabel = null;

  /** Tags text. */
  private JTextField tagsValueText = null;

  /** Add tags button. */
  private JButton addTagsButton = null;

  /** Remove tags button. */
  private JButton removeTagsButton = null;

  /** Creation date label. */
  private JLabel creationDateLabel = null;

  /** Closure date label. */
  private JLabel closureDateLabel = null;

  /** Last modification date label. */
  private JLabel modifiedDateLabel = null;

  /** Karma label. */
  private JLabel milestoneLabel = null;

  /** SeeAlso label. */
  private JLabel seeAlsoLabel = null;

  /** SameAs label. */
  private JLabel sameAsLabel = null;

  /** Duplicates label. */
  private JLabel duplicatesLabel = null;

  /** Duplicate value label. */
  private JLabel duplicatesValueLabel = null;

  /** Duplicates value text. */
  private JTextField duplicatesValueText = null;

  /** List of issue ID associated with the JList containing their duplicates. */
  private HashMap<IssueProfile, JList> duplicatesJListMap = null;

  /** List of issue ID associated with the JList containing their tags. */
  private HashMap<IssueProfile, JList> tagsJListMap = null;

  /** Add duplicates button. */
  private JButton addDuplicatesButton = null;

  /** Remove sameAs button. */
  private JButton removeDuplicatesButton = null;

  /** Homepage label. */
  private JLabel statusLabel = null;

  /** Weblog label. */
  private JLabel priorityLabel = null;

  /** NameSurname label. */
  private JLabel idLabel = null;

  /** Visibility label. */
  private JLabel visibilityLabel = null;

  /** Visibility text. */
  private JTextField visibilityText = null;

  /** Email text. */
  private JTextField assignedToText = null;

  /** Nickname text. */
  private JTextField typeText = null;

  /** Homepage text. */
  private JTextField statusText = null;

  /** Weblog text. */
  private JTextField priorityText = null;

  /** ID text. */
  private JTextField idText = null;

  /** Milestone text. */
  private JTextField milestoneText = null;

  /** Creation date text. */
  private JFormattedTextField creationDateText = null;

  /** Closure date text. */
  private JFormattedTextField closureDateText = null;

  /** MOdified date text. */
  private JFormattedTextField modifiedDateText = null;

  /** Password text. */
  private JPasswordField passwordText = null;

  /** List of skills. */
  private JList listDuplicates = null;

  /** List of skills. */
  private JList listSeeAlso = null;

  /** List of skills. */
  private JList listSameAs = null;

  /** List of tags. */
  private JList listTags = null;

  /** Profile Panels dimension. */
  // private Dimension profilePanelDimension = new Dimension(800, 200);
  /** Search button. */
  private JButton okButton = null;

  /** Search button. */
  private JButton searchButton = null;

  /** Refresh button. */
  private JButton refreshButton = null;

  /** Save button. */
  private JButton saveButton = null;

  /**
   * RDF serialization language used to obtain the currently displayed data.
   */
  private String language = null;

  /**
   * User (identified by its email) whose correspondent panel is currently in an editing mode.
   */
  private IssueProfile profileInEditingMode = null;

  /**
   * Auto-generated serial version ID
   */
  private static final long serialVersionUID = 2927369587956956550L;

  public IssuesPanel(LinkedServiceDataUI mainframe) {
    this.mainframe = mainframe;
    profilesList = new HashMap<IssueProfile, LinkedList<JTextField>>();
    // resetPanel();
  }

  // public static void main(String[] args){
  // try {
  // SensorBaseClient.registerUser("http://localhost:9876/sensorbase/",
  // "holatest@hackystat.org");
  // }
  // catch (SensorBaseClientException e) {
  // // TODO Auto-generated catch block
  // e.printStackTrace();
  // }
  // }

  private void refreshProfiles() {
    profilesList = new HashMap<IssueProfile, LinkedList<JTextField>>();
    profilesModelList = new LinkedList<Model>();
    duplicatesJListMap = new HashMap<IssueProfile, JList>();
    tagsJListMap = new HashMap<IssueProfile, JList>();
    profileInEditingMode = null;
    disableAllJTextFields();
    displayWaitingDialog();
    LinkedList<JTextField> textlist = null;
    this.language = mainframe.getLiSeDClient().getLanguage();
    try {
      issuesListModel = mainframe.getLiSeDClient().getIssuesList();
      if (issuesListModel != null) {
        LinkedServiceDataResource.printModel(issuesListModel);
        NodeIterator nodit = issuesListModel.listObjects();
        RDFNode nod = null;
        Model tmpModel = null;
        String issueuri = null;
        while (nodit.hasNext()) {
          nod = nodit.next();
          if (nod.isLiteral()) {
            issueuri = ((Literal) nod).getLexicalForm();
          }
          else if (nod.isResource() && !nod.isAnon()) {
            issueuri = ((Resource) nod).getURI();
          }
          if (!issueuri.equals(RDF.Bag.getURI())
          // && !! issueuri.endsWith("hackystat.org")
          ) {
            try {
              tmpModel = mainframe.getLiSeDClient().getUriIssueAsLinkedData(issueuri);
            }
            catch (LinkedServiceDataClientException e) {
              JOptionPane.showMessageDialog(this,
                  "Unable to retrieve issue profile for issue ID = " + issueuri + ".",
                  "Hackystat - Error Message", JOptionPane.ERROR_MESSAGE);
              tmpModel = null;
            }
            if (tmpModel != null) {
              profilesModelList.add(tmpModel);
            }
          }
        }
        StmtIterator it = null;
        IssueProfile profile = null;
        Statement statement = null;
        Property predicate = null;
        String object = null;
        for (Model model : profilesModelList) {
          it = model.listStatements();
          profile = new IssueProfile();
          while (it.hasNext()) {
            statement = it.next();
            predicate = statement.getPredicate();
            nod = statement.getObject();
            if (nod.isLiteral()) {
              object = ((Literal) nod).getLexicalForm();
            }
            else if (nod.isResource() && !nod.isAnon()) {
              object = ((Resource) nod).getURI();
            }
            if (predicate.equals(BaetleVocab.ASSIGNED_TO)) {
              profile.assignedTo = object;
            }
            else if (predicate.equals(BaetleVocab.CREATED)) {
              profile.creationDate = object;
            }
            else if (predicate.equals(RDF.type)) {
              profile.type = object;
            }
            else if (predicate.equals(BaetleVocab.TARGET_MILESTONE)) {
              profile.milestone = object;
            }
            else if (predicate.equals(BaetleVocab.PRIORITY)) {
              profile.priority = object;
            }
            else if (predicate.equals(BaetleVocab.NAME)) {
              profile.id = object;
            }
            else if (predicate.equals(HackystatVocab.CLOSED_TIME)) {
              profile.closureDate = object;
            }
            else if (predicate.equals(HackystatVocab.MODIFIED_TIME)) {
              profile.modifiedDate = object;
            }
            else if (predicate.equals(BaetleVocab.STATUS)) {
              profile.status = object;
            }
            else if (predicate.equals(CommontagVocab.TAGGED)) {
              profile.addTag(object);
            }
            else if (predicate.equals(OWL.sameAs)) {
              profile.addSameAs(object);
            }
            else if (predicate.equals(BaetleVocab.DUPLICATE)) {
              profile.addDuplicate(object);
            }
            else if (predicate.equals(RDFS.seeAlso)) {
              profile.addSeeAlso(object);
            }
            else if (predicate.equals(HackystatVocab.PRIVACY_LEVEL)) {
              profile.visibility = object;
            }
          }
          textlist = makeJTextFields(profile);
          addDuplicatesJList(profile);
          addTagsJList(profile);
          profilesList.put(profile, textlist);
        }
      }
    }
    catch (LinkedServiceDataClientException e) {
      JOptionPane.showMessageDialog(this, e.getMessage(), "Hackystat - Error Message",
          JOptionPane.ERROR_MESSAGE);
      e.printStackTrace();
    }
    finally {
      disposeDialog();
    }
  }

  @Override
  public void keyPressed(KeyEvent e) {
    // TODO Auto-generated method stub

  }

  @Override
  public void keyReleased(KeyEvent e) {
    // TODO Auto-generated method stub

  }

  @Override
  public void keyTyped(KeyEvent e) {
    // TODO Auto-generated method stub

  }

  private void enableJTextFieldsToBeEdited(IssueProfile profile) {
    LinkedList<JTextField> jtextfieldsList = null;
    if (profile != null && profilesList.containsKey(profile)) {
      jtextfieldsList = profilesList.get(profile);
      for (int i = 0; i < jtextfieldsList.size(); i++) {
        if (i != 1) {
          jtextfieldsList.get(i).setEditable(true);
          jtextfieldsList.get(i).setEnabled(true);
        }
      }
    }
  }

  private void disableAllJTextFields(IssueProfile profile) {
    LinkedList<JTextField> jtextfieldsList = null;
    if (profile != null && profilesList.containsKey(profile)) {
      jtextfieldsList = profilesList.get(profile);
      for (JTextField field : jtextfieldsList) {
        field.setEditable(false);
      }
    }
  }

  private void disableAllJTextFields() {
    LinkedList<JTextField> jtextfieldsList = null;
    Iterator<IssueProfile> it = profilesList.keySet().iterator();
    IssueProfile profile = null;
    while (it.hasNext() && jtextfieldsList == null) {
      profile = it.next();
      jtextfieldsList = profilesList.get(profile);
      for (JTextField field : jtextfieldsList) {
        field.setEditable(false);
      }
    }
  }

  @Override
  public void actionPerformed(ActionEvent e) {
    Object source = e.getSource();
    String id = null;
    // System.out.println("ACTION PERFORMED!!");
    // System.out.println("e.getActionCommand()="+e.getActionCommand());
    if (source.equals(clearCacheButton)) {

      try {
        mainframe.clearServerCache();
      }
      catch (LinkedServiceDataClientException e1) {
        JOptionPane.showMessageDialog(this, e1.getMessage(), "Hackystat - Error Message",
            JOptionPane.ERROR_MESSAGE);
        e1.printStackTrace();
      }

    }
    else if (source.equals(triplifyAllButton)) {

      Iterator<Model> it = profilesModelList.iterator();
      Model model = null;
      if (it.hasNext()) {
        model = it.next();
      }
      while (it.hasNext()) {
        model = model.union(it.next());
      }
      String serializedModel = mainframe.getLiSeDClient().serializeRDFModel(model, this.language);
      displayRDFContentDialog(serializedModel);

    }
    else if (e.getActionCommand().startsWith(TRIPLIFYPREFIX)) {

      id = e.getActionCommand().split("_")[1];
      Iterator<Model> it = profilesModelList.iterator();
      String serializedModel = null;
      Model model = null;
      while (it.hasNext() && serializedModel == null) {
        model = it.next();
        if (model.contains(null, BaetleVocab.NAME, id)) {
          serializedModel = mainframe.getLiSeDClient().serializeRDFModel(model, this.language);
          displayRDFContentDialog(serializedModel);
        }
      }

    }
    else if (e.getActionCommand().startsWith(EDITPREFIX)) {

      if (profileInEditingMode == null) {
        id = e.getActionCommand().split("_")[1];
        Iterator<IssueProfile> it = profilesList.keySet().iterator();
        IssueProfile profile = null, searchedProfile = null;
        while (it.hasNext() && searchedProfile == null) {
          profile = it.next();
          if (profile.id.equals(id)) {
            searchedProfile = profile;
          }
        }
        profileInEditingMode = searchedProfile;
        enableJTextFieldsToBeEdited(profileInEditingMode);
        JOptionPane.showMessageDialog(this, "Enter desired changes into the editable fields.",
            "Hackystat - Message", JOptionPane.PLAIN_MESSAGE);
        refresh();
      }
      else {
        JOptionPane.showMessageDialog(this, "You can't edit more than one issue at a time",
            "Hackystat - Error Message", JOptionPane.ERROR_MESSAGE);
        return;
      }

    }
    else if (e.getActionCommand().startsWith(SAVEPREFIX)) {
      id = e.getActionCommand().split("_")[1];
      LinkedList<JTextField> jtextfieldsList = null;
      SensorData issueObj = null;
      String visibility = null, assignedTo = null, type = null, status = null, priority = null, milestone = null, creation = null, closure = null, modified = null;
      jtextfieldsList = profilesList.get(profileInEditingMode);
      issueObj = new SensorData();
      visibility = jtextfieldsList.get(0).getText();
      assignedTo = jtextfieldsList.get(2).getText();
      type = jtextfieldsList.get(3).getText();
      status = jtextfieldsList.get(4).getText();
      priority = jtextfieldsList.get(5).getText();
      milestone = jtextfieldsList.get(6).getText();
      creation = jtextfieldsList.get(7).getText();
      modified = jtextfieldsList.get(8).getText();
      closure = jtextfieldsList.get(9).getText();
      /**
       * Only those properties which have been actually modified are posted to increase performance.
       */
      if (!visibility.equals(profileInEditingMode.visibility)) {
        issueObj.addProperty(HackystatConstants.SENSORDATA_VISIBILITY, visibility);
      }
      if (assignedTo != null && !assignedTo.equals(profileInEditingMode.assignedTo)
          && assignedTo.trim() != "") {
        issueObj.addProperty(HackystatConstants.ISSUE_OWNER_PROPERTY_KEY, assignedTo);
      }
      if (type != null && !type.equals(profileInEditingMode.type) && type.trim() != "") {
        issueObj.addProperty(HackystatConstants.ISSUE_TYPE_PROPERTY_KEY, type);
      }
      if (!status.equals(profileInEditingMode.status) && status.trim() != "") {
        issueObj.addProperty(HackystatConstants.ISSUE_STATUS_PROPERTY_KEY, status);
      }
      if (!priority.equals(profileInEditingMode.priority) && priority.trim() != "") {
        issueObj.addProperty(HackystatConstants.ISSUE_PRIORITY_PROPERTY_KEY, priority);
      }
      if (!milestone.equals(profileInEditingMode.milestone) && milestone.trim() != "") {
        issueObj.addProperty(HackystatConstants.ISSUE_MILESTONE_PROPERTY_KEY, milestone);
      }
      if (!creation.equals(profileInEditingMode.creationDate) && creation.trim() != "") {
        issueObj.addProperty(HackystatConstants.ISSUE_OPENED_TIME_PROPERTY_KEY, creation);
      }
      if (!closure.equals(profileInEditingMode.closureDate) && closure.trim() != "") {
        issueObj.addProperty(HackystatConstants.ISSUE_CLOSED_TIME_PROPERTY_KEY, closure);
      }
      if (!modified.equals(profileInEditingMode.modifiedDate) && modified.trim() != "") {
        issueObj.addProperty(HackystatConstants.ISSUE_MODIFIED_TIME_PROPERTY_KEY, modified);
      }
      String dups = getNewDuplicates();
      if (dups != null) {
        issueObj.addProperty(HackystatConstants.ISSUE_DUPLICATES_LIST, dups);
      }
      dups = getNewTags();
      if (dups != null) {
        issueObj.addProperty(HackystatConstants.ISSUE_TAGS_LIST, dups);
      }
      issueObj.addProperty(HackystatConstants.ISSUE_ID_PROPERTY_KEY, id);
      issueObj.setOwner(mainframe.getLoggedUser());
      issueObj.setTimestamp(Tstamp.makeTimestamp());
      try {
        mainframe.getLiSeDClient().addIssueData(issueObj);
        JOptionPane.showMessageDialog(this, "Your new entered data have been saved.",
            "Hackystat - Message", JOptionPane.PLAIN_MESSAGE);
      }
      catch (LinkedServiceDataClientException e2) {
        JOptionPane.showMessageDialog(this, e2.getMessage(), "Hackystat - Error Message",
            JOptionPane.ERROR_MESSAGE);
        e2.printStackTrace();
        refreshProfiles();
      }
      disableAllJTextFields(profileInEditingMode);
      profileInEditingMode = null;
      refresh();

    }
    else if (source.equals(refreshButton)) {
      if (mainframe.isLogged()) {
        mainframe.getLiSeDClient().clearLocalCache();
        JOptionPane.showMessageDialog(this, "Local cache for the logged user has been cleared.",
            "Hackystat - Message", JOptionPane.PLAIN_MESSAGE);
        resetPanel();
      }
    }
    else if (source.equals(searchButton)) {
      new IssueSearchWizard(mainframe);
    }
    else if (source.equals(addDuplicatesButton)) {
      String text = duplicatesValueText.getText();
      if (text != null && !text.trim().equals("")) {
        JList jlist = duplicatesJListMap.get(profileInEditingMode);
        DefaultListModel model = (DefaultListModel) jlist.getModel();
        model.addElement(text);
        jlist.repaint();
      }
    }
    else if (source.equals(addTagsButton)) {
      String text = tagsValueText.getText();
      if (text != null && !text.trim().equals("")) {
        JList jlist = tagsJListMap.get(profileInEditingMode);
        DefaultListModel model = (DefaultListModel) jlist.getModel();
        model.addElement(text);
        jlist.repaint();
      }
    }
    else if (source.equals(removeDuplicatesButton)) {
      JList jlist = duplicatesJListMap.get(profileInEditingMode);
      int index = jlist.getSelectedIndex();
      ((DefaultListModel) jlist.getModel()).remove(index);
      jlist.repaint();
    }
    else if (source.equals(removeTagsButton)) {
      JList jlist = tagsJListMap.get(profileInEditingMode);
      int index = jlist.getSelectedIndex();
      ((DefaultListModel) jlist.getModel()).remove(index);
      jlist.repaint();
    }
  }

  private String getNewDuplicates() {
    String ret = "";
    DefaultListModel model = (DefaultListModel) duplicatesJListMap.get(profileInEditingMode)
        .getModel();
    boolean newElem = false;
    if (model.getSize() != profileInEditingMode.getDuplicates().size()) {
      newElem = true;
    }
    for (int i = 0; i < model.getSize(); i++) {
      ret += model.get(i) + HackystatConstants.SEPARATOR1_ID;
      if (!newElem) {
        if (!profileInEditingMode.getDuplicates().contains(model.get(i))) {
          newElem = true;
        }
      }
    }
    if (!newElem) {
      ret = null;
    }
    return ret;
  }

  private String getNewTags() {
    String ret = "";
    DefaultListModel model = (DefaultListModel) tagsJListMap.get(profileInEditingMode).getModel();
    boolean newElem = false;
    if (model.getSize() != profileInEditingMode.getTags().size()) {
      newElem = true;
    }
    for (int i = 0; i < model.getSize(); i++) {
      ret += model.get(i) + HackystatConstants.SEPARATOR1_ID;
      if (!newElem) {
        if (!profileInEditingMode.getTags().contains(model.get(i))) {
          newElem = true;
        }
      }
    }
    if (!newElem) {
      ret = null;
    }
    return ret;
  }

  public void refresh() {
    this.removeAll();
    JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
    panel.setBackground(Color.WHITE);
    if (mainframe.isLogged()) {
      clearCacheButton = new JButton("Clear cache", LinkedServiceDataUI.clearIcon);
      searchButton = new JButton("Search", LinkedServiceDataUI.searchIcon);
      refreshButton = new JButton("Refresh", LinkedServiceDataUI.refreshIcon);
      triplifyAllButton = new JButton("Triplify All", LinkedServiceDataUI.triplifyIcon);
      panel.add(mainframe.getHeader(this, searchButton, refreshButton, triplifyAllButton,
          clearCacheButton, "Issues"));
    }

    JPanel subpanel = null;
    for (IssueProfile profile : profilesList.keySet()) {
      subpanel = new JPanel();
      subpanel.setLayout(new BoxLayout(subpanel, BoxLayout.Y_AXIS));
      subpanel.setBackground(Color.WHITE);
      LinkedList<JTextField> textlist = profilesList.get(profile);
      subpanel.add(fillInUserProfileData1(profile, textlist));
      subpanel.add(getActionsOnProfile(profile.id));
      subpanel.setBorder(BorderFactory.createLineBorder(Color.blue));
      panel.add(subpanel);
    }

    panel.setBackground(Color.white);
    JScrollPane listScrollPane = new JScrollPane(panel);
    listScrollPane = mainframe.initSubPanelScrollPane(listScrollPane);
    this.add(listScrollPane);
    this.validate();
  }

  private JPanel getActionsOnProfile(String id) {
    JPanel horiz = new JPanel();
    horiz.setLayout(new BoxLayout(horiz, BoxLayout.X_AXIS));
    horiz.add(Box.createHorizontalStrut(this.getSize().width / 2));
    horiz.setBackground(Color.white);
    actionLabel = new JLabel();
    actionLabel = mainframe.initLabel(actionLabel, "Actions:");
    horiz.add(actionLabel);
    horiz.add(Box.createHorizontalStrut(5));

    if (profileInEditingMode != null && profileInEditingMode.id.equals(id)) {
      saveButton = new JButton("Save");
      saveButton = mainframe.initButton(saveButton, this, mainframe.buttonDimension,
          "Save changes.");
      saveButton.setActionCommand(SAVEPREFIX + id);
      horiz.add(saveButton);
    }
    else {
      editButton = new JButton("Edit");
      editButton = mainframe.initButton(editButton, this, mainframe.buttonDimension,
          "Edit data about this issue.");
      editButton.setActionCommand(EDITPREFIX + id);
      horiz.add(editButton);
    }
    horiz.add(Box.createHorizontalStrut(5));

    triplifyOneButton = new JButton("Triplify", LinkedServiceDataUI.triplifyIcon);
    triplifyOneButton = mainframe.initButton(triplifyOneButton, this, mainframe.buttonDimension,
        "Get RDF representation of this issue");
    triplifyOneButton.setActionCommand(TRIPLIFYPREFIX + id);
    horiz.add(triplifyOneButton);
    horiz.add(Box.createHorizontalGlue());
    return horiz;
  }

  private LinkedList<JTextField> makeJTextFields(IssueProfile profile) {
    LinkedList<JTextField> textlist = new LinkedList<JTextField>();
    visibilityText = new JTextField(1);
    visibilityText = mainframe.initTextField(visibilityText, profile.visibility, false);
    textlist.add(visibilityText);
    idText = new JTextField(5);
    idText = mainframe.initTextField(idText, profile.id, false);
    textlist.add(idText);
    assignedToText = new JTextField(10);
    assignedToText = mainframe.initTextField(assignedToText, profile.assignedTo, false);
    textlist.add(assignedToText);
    typeText = new JTextField(10);
    typeText = mainframe.initTextField(typeText, profile.type, false);
    textlist.add(typeText);
    statusText = new JTextField(10);
    statusText = mainframe.initTextField(statusText, profile.status, false);
    textlist.add(statusText);
    priorityText = new JTextField(10);
    priorityText = mainframe.initTextField(priorityText, profile.priority, false);
    textlist.add(priorityText);
    milestoneText = new JTextField(10);
    milestoneText = mainframe.initTextField(milestoneText, profile.milestone, false);
    textlist.add(milestoneText);
    String tooltip = "Use the date format 'yyyy-M-d' please";
    creationDateText = new JFormattedTextField(10);
    creationDateText = mainframe.initFormattedDateTextField(creationDateText, profile.creationDate,
        false, tooltip);
    textlist.add(creationDateText);
    modifiedDateText = new JFormattedTextField(10);
    modifiedDateText = mainframe.initFormattedDateTextField(modifiedDateText, profile.modifiedDate,
        false, tooltip);
    textlist.add(modifiedDateText);

    closureDateText = new JFormattedTextField(10);
    closureDateText = mainframe.initFormattedDateTextField(closureDateText, profile.closureDate,
        false, tooltip);
    textlist.add(closureDateText);

    return textlist;
  }

  /**
   * Monitor a correct displaying of this tab panel while the user is browsing between tabs. If he
   * is logged then the list of profiles for this panel is already updated and then it's not refresh
   * now.
   */
  public void prepareDisplaying() {
    if (!mainframe.isLogged()) {
      profilesList = new HashMap<IssueProfile, LinkedList<JTextField>>();
    }
    else if (profilesList.isEmpty()) {
      refreshProfiles();
    }
    refresh();
  }

  /**
   * Forces the resetting of the whole panel and re-fills it only if the current user is logged.
   * This is used after changes to the authentication state.
   */
  public void resetPanel() {
    this.profilesList = new HashMap<IssueProfile, LinkedList<JTextField>>();
    if (mainframe.isLogged()) {
      refreshProfiles();
    }
    refresh();
  }

  private void addDuplicatesJList(IssueProfile profile) {
    LinkedList<String> duplist = profile.getDuplicates();
    DefaultListModel model = new DefaultListModel();
    for (String dup : duplist) {
      model.addElement(dup);
    }
    JList jlist = new JList(model);
    jlist = mainframe.initJList(jlist);
    duplicatesJListMap.put(profile, jlist);
  }

  private void addTagsJList(IssueProfile profile) {
    LinkedList<String> taglist = profile.getTags();
    DefaultListModel model = new DefaultListModel();
    for (String tag : taglist) {
      model.addElement(tag);
    }
    JList jlist = new JList(model);
    jlist = mainframe.initJList(jlist);
    tagsJListMap.put(profile, jlist);
  }

  private JPanel fillInUserProfileData1(IssueProfile profile, LinkedList<JTextField> textlist) {
    JPanel horiz = new JPanel();
    horiz.setLayout(new BoxLayout(horiz, BoxLayout.X_AXIS));
    horiz.setBackground(Color.white);
    JPanel vertic = null;
    initLabelHeaders1();

    vertic = new JPanel();
    vertic.setLayout(new BoxLayout(vertic, BoxLayout.Y_AXIS));
    vertic.setBackground(Color.white);
    vertic.add(visibilityLabel);
    vertic.add(Box.createVerticalStrut(1));
    vertic.add(textlist.get(0));
    vertic.add(Box.createVerticalStrut(3));
    vertic.add(idLabel);
    vertic.add(Box.createVerticalStrut(1));
    vertic.add(textlist.get(1));
    vertic.add(Box.createVerticalStrut(3));
    vertic.add(assignedToLabel);
    vertic.add(Box.createVerticalStrut(1));
    vertic.add(textlist.get(2));
    vertic.add(Box.createVerticalStrut(3));
    vertic.add(typeLabel);
    vertic.add(Box.createVerticalStrut(1));
    vertic.add(textlist.get(3));
    vertic.add(Box.createVerticalStrut(3));
    vertic.add(statusLabel);
    vertic.add(Box.createVerticalStrut(1));
    vertic.add(textlist.get(4));
    horiz.add(vertic);

    vertic = new JPanel();
    vertic.setLayout(new BoxLayout(vertic, BoxLayout.Y_AXIS));
    vertic.setBackground(Color.white);
    vertic.add(priorityLabel);
    vertic.add(Box.createVerticalStrut(1));
    vertic.add(textlist.get(5));
    vertic.add(Box.createVerticalStrut(3));
    vertic.add(milestoneLabel);
    vertic.add(Box.createVerticalStrut(1));
    vertic.add(textlist.get(6));
    vertic.add(Box.createVerticalStrut(3));
    vertic.add(creationDateLabel);
    vertic.add(Box.createVerticalStrut(1));
    vertic.add(textlist.get(7));
    vertic.add(Box.createVerticalStrut(3));
    vertic.add(modifiedDateLabel);
    vertic.add(Box.createVerticalStrut(1));
    vertic.add(textlist.get(8));
    vertic.add(Box.createVerticalStrut(3));
    vertic.add(closureDateLabel);
    vertic.add(Box.createVerticalStrut(1));
    vertic.add(textlist.get(9));
    horiz.add(vertic);

    vertic = new JPanel();
    vertic.setLayout(new BoxLayout(vertic, BoxLayout.Y_AXIS));
    vertic.setBackground(Color.white);

    listDuplicates = duplicatesJListMap.get(profile);
    JScrollPane listScrollPane = new JScrollPane(listDuplicates);
    listScrollPane = mainframe.initJListScrollPane(listScrollPane);
    if (profileInEditingMode != null && profileInEditingMode == profile) {
      if (addDuplicatesButton == null) {
        addDuplicatesButton = new JButton("Add >>");
        addDuplicatesButton = mainframe.initButton(addDuplicatesButton, this,
            mainframe.buttonDimension, "Add the inserted duplicates' " + "URI to the " + "list");
      }
      if (removeDuplicatesButton == null) {
        removeDuplicatesButton = new JButton("Remove <<");
        removeDuplicatesButton = mainframe.initButton(removeDuplicatesButton, this,
            mainframe.buttonDimension, "Remove the inserted duplicates' " + "URI to the " + "list");
      }
      duplicatesValueText = new JTextField(10);
      duplicatesValueText = mainframe.initTextField(duplicatesValueText, "", true);
      vertic.add(mainframe.addJListFillingComponent(duplicatesValueLabel, duplicatesValueText,
          addDuplicatesButton, removeDuplicatesButton, duplicatesLabel, listScrollPane, null));
    }
    else {
      vertic.add(duplicatesLabel);
      vertic.add(Box.createVerticalStrut(1));
      vertic.add(listScrollPane);
    }
    vertic.add(Box.createVerticalStrut(3));

    listTags = tagsJListMap.get(profile);
    listScrollPane = new JScrollPane(listTags);
    listScrollPane = mainframe.initJListScrollPane(listScrollPane);
    if (profileInEditingMode != null && profileInEditingMode == profile) {
      if (addTagsButton == null) {
        addTagsButton = new JButton("Add >>");
        addTagsButton = mainframe.initButton(addTagsButton, this, mainframe.buttonDimension,
            "Add the inserted tag to the " + "list");
      }
      if (removeTagsButton == null) {
        removeTagsButton = new JButton("Remove <<");
        removeTagsButton = mainframe.initButton(removeTagsButton, this, mainframe.buttonDimension,
            "Remove the inserted duplicates' " + "URI to the " + "list");
      }
      tagsValueText = new JTextField(10);
      tagsValueText = mainframe.initTextField(tagsValueText, "", true);
      vertic.add(mainframe.addJListFillingComponent(tagsValueLabel, tagsValueText, addTagsButton,
          removeTagsButton, tagsLabel, listScrollPane, null));
    }
    else {
      vertic.add(tagsLabel);
      vertic.add(Box.createVerticalStrut(1));
      vertic.add(listScrollPane);
    }
    horiz.add(vertic);

    vertic = new JPanel();
    vertic.setLayout(new BoxLayout(vertic, BoxLayout.Y_AXIS));
    vertic.setBackground(Color.white);
    vertic.add(sameAsLabel);
    vertic.add(Box.createVerticalStrut(1));
    DefaultListModel listModel = new DefaultListModel();
    for (String sameAs : profile.getSameAs()) {
      listModel.addElement(sameAs);
    }
    listSameAs = new JList(listModel);
    listSameAs = mainframe.initJList(listSameAs);
    listScrollPane = new JScrollPane(listSameAs);
    listScrollPane = mainframe.initJListScrollPane(listScrollPane);
    vertic.add(listScrollPane);
    vertic.add(Box.createVerticalStrut(3));
    vertic.add(seeAlsoLabel);
    vertic.add(Box.createVerticalStrut(1));
    listModel = new DefaultListModel();
    for (String seeAlso : profile.getSeeAlso()) {
      listModel.addElement(seeAlso);
    }
    listSeeAlso = new JList(listModel);
    listSeeAlso = mainframe.initJList(listSeeAlso);
    listScrollPane = new JScrollPane(listSeeAlso);
    listScrollPane = mainframe.initJListScrollPane(listScrollPane);
    vertic.add(listScrollPane);

    horiz.add(vertic);

    return horiz;
  }

  private void initLabelHeaders1() {
    visibilityLabel = new JLabel();
    visibilityLabel = mainframe.initLabel(visibilityLabel, "Visibility:");

    idLabel = new JLabel();
    idLabel = mainframe.initLabel(idLabel, "ID:");

    assignedToLabel = new JLabel();
    assignedToLabel = mainframe.initLabel(assignedToLabel, "Assigned to:");

    typeLabel = new JLabel();
    typeLabel = mainframe.initLabel(typeLabel, "Type:");

    statusLabel = new JLabel();
    statusLabel = mainframe.initLabel(statusLabel, "Status:");

    priorityLabel = new JLabel();
    priorityLabel = mainframe.initLabel(priorityLabel, "Priority:");

    milestoneLabel = new JLabel();
    milestoneLabel = mainframe.initLabel(milestoneLabel, "Milestone:");

    creationDateLabel = new JLabel();
    creationDateLabel = mainframe.initLabel(creationDateLabel, "Creation date:");

    modifiedDateLabel = new JLabel();
    modifiedDateLabel = mainframe.initLabel(modifiedDateLabel, "Last modification date:");

    closureDateLabel = new JLabel();
    closureDateLabel = mainframe.initLabel(closureDateLabel, "Closure date:");

    seeAlsoLabel = new JLabel();
    seeAlsoLabel = mainframe.initLabel(seeAlsoLabel, "See also:");

    sameAsLabel = new JLabel();
    sameAsLabel = mainframe.initLabel(sameAsLabel, "Same as:");

    duplicatesLabel = new JLabel();
    duplicatesLabel = mainframe.initLabel(duplicatesLabel, "Duplicates:");

    duplicatesValueLabel = new JLabel();
    duplicatesValueLabel = mainframe.initLabel(duplicatesValueLabel, "Duplicate URI:");

    tagsLabel = new JLabel();
    tagsLabel = mainframe.initLabel(tagsLabel, "Tags:");

    tagsValueLabel = new JLabel();
    tagsValueLabel = mainframe.initLabel(tagsValueLabel, "Tag value:");
  }

  private void displayWaitingDialog() {
    JProgressBar pb = new JProgressBar(0, 100);
    pb.setPreferredSize(new Dimension(175, 20));
    pb.setString("wait");
    pb.setIndeterminate(true);
    pb.setStringPainted(true);
    pb.setValue(0);
    JLabel label = new JLabel("The list of issues is being downloaded "
        + "from LiSeD service. Please wait...");
    JPanel center_panel = new JPanel();
    center_panel.setLayout(new BoxLayout(center_panel, BoxLayout.Y_AXIS));
    center_panel.add(label);
    center_panel.add(Box.createVerticalStrut(2));
    center_panel.add(pb);
    dialog = new JDialog(mainframe, "Please wait...");

    dialog.setLocationRelativeTo(null); // center on screen
    dialog.setLocation(550, 25); // position by coordinates
    dialog.toFront(); // raise above other java windows

    dialog.getContentPane().add(center_panel, BorderLayout.CENTER);
    dialog.pack();
    dialog.setVisible(true);
    this.setEnabled(false);
    mainframe.setEnabled(false);
    dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
    dialog.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent we) {
        setEnabled(true);
        mainframe.setEnabled(true);
        dialog.dispose();
        dialog = null;
      }
    });
    // dialog.setBackground(Color.white);
  }

  public void disposeDialog() {
    this.setEnabled(true);
    mainframe.setEnabled(true);
    if (dialog != null) {
      dialog.dispose();
    }
  }

  public void displayPasswordRequiredDialog(String email) {
    JPanel center_panel = new JPanel();
    center_panel.setLayout(new BoxLayout(center_panel, BoxLayout.Y_AXIS));
    JLabel label = new JLabel("Insert the selected user's password:");
    center_panel.add(label);
    center_panel.add(Box.createVerticalStrut(2));
    passwordText = new JPasswordField();
    center_panel.add(passwordText);
    center_panel.add(Box.createVerticalStrut(5));
    okButton = new JButton();
    okButton.setMnemonic(KeyEvent.VK_S);
    okButton.setFont(new Font("Dialog", java.awt.Font.BOLD, mainframe.buttonFontSize));
    okButton.setText("OK");
    okButton.addActionListener(this);
    okButton.setSize(mainframe.triplifyButtonDimension);
    okButton.setPreferredSize(mainframe.triplifyButtonDimension);
    okButton.setMaximumSize(mainframe.triplifyButtonDimension);
    okButton.setMinimumSize(mainframe.triplifyButtonDimension);
    okButton.setActionCommand(OKPREFIX + email);
    center_panel.add(okButton);

    dialog = new JDialog(mainframe, "Insert Password");

    dialog.setLocationRelativeTo(null); // center on screen
    // dialog.setLocation(550,25); // position by coordinates
    dialog.toFront(); // raise above other java windows

    dialog.getContentPane().add(center_panel, BorderLayout.CENTER);
    dialog.pack();
    dialog.setVisible(true);
    this.setEnabled(false);
    mainframe.setEnabled(false);
    dialog.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent we) {
        setEnabled(true);
        mainframe.setEnabled(true);
        dialog.dispose();
        dialog = null;
      }
    });
    dialog.setBackground(Color.white);
  }

  public void displayRDFContentDialog(String serializedModel) {
    JTextArea area = new JTextArea(serializedModel);
    area.setColumns(mainframe.jdialogTextAreaNumCols);
    area.setRows(mainframe.jdialogTextAreaNumRows);
    area.setEditable(false);
    JScrollPane listScrollPane = new JScrollPane(area);
    listScrollPane.setPreferredSize(mainframe.jdialogAreaDimension);
    listScrollPane.setMaximumSize(mainframe.jdialogAreaDimension);
    listScrollPane.setMinimumSize(mainframe.jdialogAreaDimension);
    JLabel label = new JLabel("RDF serialization using the language " + this.language);
    JPanel center_panel = new JPanel();
    center_panel.setLayout(new BoxLayout(center_panel, BoxLayout.Y_AXIS));
    center_panel.add(label);
    center_panel.add(Box.createVerticalStrut(5));
    center_panel.add(listScrollPane);
    JDialog dialog1 = new JDialog(mainframe, "RDF User Profiles");

    dialog1.setLocationRelativeTo(null); // center on screen
    dialog1.setLocation(550, 25); // position by coordinates
    dialog1.toFront(); // raise above other java windows

    dialog1.getContentPane().add(center_panel, BorderLayout.CENTER);
    dialog1.pack();
    dialog1.setVisible(true);

    dialog1.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
  }
}
